//
//  ViewController.m
//  caitu
//
//  Created by 楼楚 on 15/10/21.
//  Copyright © 2015年 Chu Lou. All rights reserved.
//

#import "ViewController.h"
#import "Question.h"

#define kButtonWidth 35
#define kButtonHeight 35
#define kButtonMargin 10
#define kTotoCol  7

@interface ViewController ()
@property (weak, nonatomic) IBOutlet UIButton *iconButton;
@property (weak, nonatomic) IBOutlet UILabel *numLabel;
@property (weak, nonatomic) IBOutlet UILabel *titleLabel;
@property (weak, nonatomic) IBOutlet UIButton *nextQuestionButton;
@property (weak, nonatomic) IBOutlet UIView *answerView;
@property (weak, nonatomic) IBOutlet UIView *optionsView;
@property (weak, nonatomic) IBOutlet UIButton *scoreButton;

@property (nonatomic,strong) UIButton *cover;

@property (nonatomic,strong) NSArray *questions;
//题目索引
@property(nonatomic,assign) int index;

@end

@implementation ViewController
- (NSArray *)questions
{
    if (_questions == nil) {
        _questions = [Question questions];
    }
    return  _questions;
}
- (UIButton *)cover
{
    if (_cover == nil) {
        _cover = [[UIButton alloc]initWithFrame:self.view.bounds];
        _cover.backgroundColor = [UIColor colorWithWhite:0.0 alpha:0.5];
        [self.view addSubview:_cover];
        _cover.alpha = 0.0;
        [_cover addTarget:self action:@selector(bigImage) forControlEvents:UIControlEventTouchUpInside];
    }
    return _cover;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.index = -1;
    [self nextQuestion];

    
}
//调整状态栏颜色
- (UIStatusBarStyle) preferredStatusBarStyle
{
    return UIStatusBarStyleLightContent;
}





// 大图小图切换
- (IBAction)bigImage
{
    if (_cover.alpha == 0.0) {
        [self cover];
//    2.将图像按钮弄到最前面
//    view bringSubviewToFront 将子视图前置
    [self.view bringSubviewToFront:self.iconButton];
//    3.动画放大到最前面
    CGFloat w = self.view.bounds.size.width;
    CGFloat h = w;
    CGFloat y =( self.view.bounds.size.height - h)*0.5;
    [UIView animateWithDuration:1.0f animations:^{
        self.iconButton.frame = CGRectMake(0, y, w, h);
        self.cover.alpha = 1.0;}
     ];
 
    }else
    {
        [UIView animateWithDuration:1.0f animations:^{
//    将图像恢复初始位置
        self.iconButton.frame = CGRectMake(125, 103, 150, 150);
        _cover.alpha = 0.0;
      }];
    }

}



#pragma mark - 下一题
- (IBAction)nextQuestion
{
//    1.当前答题的索引，索引递增
    self.index++;
//    如果index已经到最后一题 提示用户
    if (self.index == self.questions.count) {
        NSLog(@"pass");
        return;
    }
//    2.从数组中按照索引取出题目模型数据
    Question *question = self.questions[self.index];
//    3.设置基本信息
    [self setupBasicInfo:question];
    
//    4.设置答案按钮
    
    [self createAnswerButtons:question];
    
    
//    5.设置备选按钮
   
    [self createOptionButtons:question];
    
}
//设置基本信息
- (void)setupBasicInfo:(Question *)question
{
    self.numLabel.text = [NSString stringWithFormat:@"%d/%lu",self.index + 1,self.questions.count];
    self.titleLabel.text = question.title;
    [self.iconButton setImage:[UIImage imageNamed:question.icon] forState:UIControlStateNormal];
    //     如果到达最后一题，禁用下一题按钮
    self.nextQuestionButton.enabled = (self.index<self.questions.count - 1);
}
//创建答案区按钮
- (void) createAnswerButtons:(Question *)question
{
    
    //      清除答题区内的所有按钮
    //      所有的控件都继承自 UIView，多态的应用
    
    for (UIButton *btn in self.answerView.subviews) {
        [btn removeFromSuperview];
    }
    CGFloat answerW = self.answerView.bounds.size.width;
    int length = question.answer.length;
    CGFloat answerX = answerW - kButtonWidth * length - kButtonMargin * (length - 1)*0.5;
    //    创建所有答案的按钮
    for (int i = 0; i < length; i ++) {
        CGFloat x = answerX + i *(kButtonMargin +kButtonWidth);
        
        UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(x, 0, kButtonWidth, kButtonHeight)];
        [btn setBackgroundImage:[UIImage imageNamed:@"btn_answer"] forState:UIControlStateNormal];
        [btn setBackgroundImage:[UIImage imageNamed:@"btn_answer_highlighted"] forState:UIControlStateHighlighted];
//         设置标题颜色
        [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        
        [self.answerView addSubview:btn];
        [btn addTarget:self action:@selector(answerClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    
 
}


//创建备选区按钮

- (void) createOptionButtons:(Question *)question
{
//问题：每次调用下一题方法时，都会重新创建21个按钮
//解决：如果按钮已经存在，只需要更改按钮标题即可
    if (self.optionsView.subviews.count !=question.options.count)
    {
//        重新创建所有按钮
        for (UIView *view in self.optionsView.subviews) {
            [view removeFromSuperview];
        }
        CGFloat optionW = self.optionsView.bounds.size.width;
        CGFloat optionX = (optionW - kTotoCol * kButtonWidth - (kTotoCol - 1)* kButtonMargin)*0.5;
        for (int i = 0;i < question.options.count; i++) {
            int row = i / kTotoCol;
            int col = i % kTotoCol;
            
            CGFloat x = optionX + col *(kButtonMargin + kButtonWidth);
            CGFloat y = row *(kButtonMargin + kButtonHeight);
            
            UIButton *btn = [[UIButton alloc]initWithFrame:CGRectMake(x, y, kButtonWidth, kButtonHeight)];
            [btn setBackgroundImage:[UIImage imageNamed:@"btn_option"] forState:UIControlStateNormal];
            [btn setBackgroundImage:[UIImage imageNamed:@"btn_option_highlighted"] forState:UIControlStateHighlighted];
            //        设置备选答案
           
            [btn setTitle:question.options[i] forState:UIControlStateNormal];
            [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
            
            [self.optionsView addSubview:btn];

            //        添加按钮监听方法
            [btn addTarget:self action:@selector(optionClick:) forControlEvents:UIControlEventTouchUpInside];
        }

    }
//    如果按钮已经存在，在点击下一题的时候，只需要设置标题即可
    int i = 0;
//    让模型打乱数据
//    [question randomOptions];
    for (UIButton *btn in self.optionsView.subviews) {
          [btn setTitle:question.options[i++] forState:UIControlStateNormal];
        
        btn.hidden = NO;
//        添加按钮监听方法
//        [btn addTarget:self action:@selector(optionClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    }


#pragma mark - 候选按钮点击方法
//候选按钮点击
- (void) optionClick:(UIButton *)button
{
    NSLog(@"%s",__func__);
//1.在答案区找到第一个文字为空的按钮
    
    UIButton *btn = [self firstAnswerButton];
//   如果没有找到按钮，直接返回
    if (btn == nil) {
//        都有字 判断胜负
        
    } else {
    
//2.将button的标题设置给答案区的按钮
    
    [btn setTitle:button.currentTitle forState:UIControlStateNormal];
    
    
//3.将button隐藏
        button.hidden = YES;
    }
//4. 判断结果
    [self judge];
}
//判断结果
- (void) judge
{
//    答案区按钮都有文字 才需要判断结果
//    遍历所有答案区的按钮
    BOOL isFull = YES;
    NSMutableString *strM = [NSMutableString string];
    for (UIButton *btn in self.answerView.subviews) {
        if (btn.currentTitle.length == 0) {
//            只要有一个按钮没有字
            isFull = NO;
            break;
        }else{
            [strM appendString:btn.currentTitle];
        }
    }
    if (isFull) {
        Question *question = self.questions[self.index];
        if ([strM isEqualToString:question.answer]) {
            NSLog(@"right");
            [self setAnswerButtonsColor:[UIColor blueColor]];
//            add score
            [self changScore:100];
//            等待0.5s 进入下一题
            [self performSelector:@selector(nextQuestion) withObject:nil afterDelay:0.5];
            
            
        }else{
            NSLog(@"wrong");
            [self setAnswerButtonsColor:[UIColor redColor]];
        }
    }
}
// 修改答题区按钮的颜色
- (void)setAnswerButtonsColor:(UIColor *)color
{
    for (UIButton *btn in self.answerView.subviews) {
        [btn setTitleColor:color forState:UIControlStateNormal];
    }
}

//1.在答案区找到第一个文字为空的按钮

- (UIButton *)firstAnswerButton
{
//    取按钮标题
//   遍历答题区所有按钮
    for (UIButton *btn in self.answerView.subviews) {
        if (btn.currentTitle.length == 0) {
            return btn;
        }
    }
    return nil;
}

#pragma mark - 答题区按钮点击方法
- (void) answerClick:(UIButton *)button
{
//    1.如果按钮区没有字 直接返回
    if(button.currentTitle.length == 0)  return;
    
//    2.如果有字，清除文字，候选区按钮重新显示
    
//     1.. 使用button的title去查找候选区对应的按钮；
    UIButton *btn = [self optionButtonWithTitle:button.currentTitle isHidden:YES];
//    2..显示对应按钮
    btn.hidden = NO;
//    3..清除button的文字
    [button setTitle:@"" forState:UIControlStateNormal];
//    4..只要点击了按钮上的文字 意味着答题区的内容不完整
    [self setAnswerButtonsColor:[UIColor blackColor]];
}

- (UIButton *)optionButtonWithTitle:(NSString *)title isHidden:(BOOL) isHidden
{
    for (UIButton *btn in self.optionsView.subviews) {
        if ([btn.currentTitle isEqualToString:title] &&btn.isHidden == isHidden) {
            return btn;
        }
    }
    return nil;
}
#pragma mark - 提示功能
- (IBAction)tipClick {
//1.把答题区中所有的按钮的清空
    for (UIButton *btn in self.answerView.subviews) {
//       用代码执行点击答题按钮的操作
        [self answerClick:btn];
    }
    
//2.把正确答案的第一个字显示在答题区
//    1. 知道答案的第一个字
    Question *question =self.questions[self.index];
    NSString *first = [question.answer substringToIndex:1];
//    取出文字对应的候选按钮
    UIButton *btn = [self optionButtonWithTitle:first isHidden:NO];
    [self optionClick:btn];
//扣分
    [self changScore:-100];
}

#pragma mark - 分数处理
- (void)changScore:(int)score
{
//      取出当前分数
    int currentScore = self.scoreButton.currentTitle.intValue;
//    使用score调整分数
    currentScore += score;
//    重新设置分数
    [self.scoreButton setTitle:[NSString stringWithFormat:@"%d",currentScore] forState:UIControlStateNormal];
}


@end
